<template>
  <div class="pagination">
    <p>{{ startNumAndEndNum }} -- currentPage:{{ pageSize }}</p>
    <button
      :disabled="currentPage == 1"
      @click="$emit('getCurrentPage', currentPage - 1)"
    >
      上一页
    </button>
    <button
      v-show="startNumAndEndNum.start > 1"
      @click="$emit('getCurrentPage', 1)"
    >
      1
    </button>
    <button v-show="startNumAndEndNum.start > 2">···</button>

    <button
      v-for="(page, index) in startNumAndEndNum.end"
      :key="index"
      :class="{ active: currentPage == page }"
      v-show="page >= startNumAndEndNum.start"
      @click="$emit('getCurrentPage', page)"
    >
      {{ page }}
    </button>

    

    <button v-show="startNumAndEndNum.end < totalPage - 1">···</button>
    <button
      v-show="startNumAndEndNum.end < totalPage"
      @click="$emit('getCurrentPage', totalPage)"
    >
      {{ totalPage }}
    </button>
    <button
      :disabled="currentPage == totalPage"
      @click="$emit('getCurrentPage', currentPage + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }}条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["currentPage", "pageSize", "total", "continuous"],
  computed: {
    //计算总页数 Math.ceil()向上取整
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    //计算连续页码的起始页与结束页的数字（连续页码为5页）
    startNumAndEndNum() {
      const { currentPage, continuous, totalPage } = this;
      let start = 0;
      let end = 0;
      //特殊情况：如果连续页码大于总共的页码：[总共4页，连续页码5页]
      if (continuous > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        //正常情况：连续页码5 总数一定大于5
        start = currentPage - parseInt(continuous / 2);
        end = currentPage + parseInt(continuous / 2);
        // 特殊情况（start数字为0｜负数）
        if (start < 1) {
          start = 1;
          end = continuous;
        }
        //特殊情况（end数字大于页码总页数）
        if (end > totalPage) {
          end = totalPage;
          start = totalPage - continuous + 1;
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="scss" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
  .active {
    background-color: orchid;
  }
}
</style>
